package com.atguigu.order.web;

import com.atguigu.common.exception.NotStockException;
import com.atguigu.order.service.OrderService;
import com.atguigu.order.vo.OrderConfirmVo;
import com.atguigu.order.vo.OrderItemVo;
import com.atguigu.order.vo.OrderSubmitVo;
import com.atguigu.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * description: OrderWebController
 * date: 2022/12/22 16:37
 * author: MR.孙
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo= orderService.confirmOrder();
        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm.html";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){

        try {
            System.out.println("订单提交的数据" + vo);
            SubmitOrderResponseVo submitOrderResponseVo= orderService.submitOrder(vo);
            if (submitOrderResponseVo.getCode()==0) {
                //提交订单成功重定向到支付页
                model.addAttribute("submitOrderResp", submitOrderResponseVo);
                return "pay";
            } else {
                //下单失败，回到订单页面
                String msg = "下单失败：";
                switch (submitOrderResponseVo.getCode()) {
                    //令牌验证不通过
                    case 1: msg += "订单信息过期, 请刷新后再次提交"; break;
                    case 2 : msg += "订单商品价格发送变化, 请确认后再次提交"; break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NotStockException) {
                String msg = "下单失败，商品无库存";
                redirectAttributes.addFlashAttribute("msg", msg);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }

}
